package com.talktalk.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import com.talktalk.entity.Friend;
import com.talktalk.entity.Message;
import com.talktalk.entity.User;
import com.talktalk.utils.MyQueryRunner;

public class UserDao {
	QueryRunner qr = new MyQueryRunner();
	
	public User findById(String id){
		try {
			return qr.query("select * from t_user where uid = ?", new BeanHandler<User>(User.class),id);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public List<Friend> findFriendsByUid(String uid) {
		try {
			String sql1 = "SELECT f.fid,u.username  "
					+"FROM t_friend f,t_user u "
					+"WHERE f.uid = ? AND u.uid = f.fid";	
			List<Map<String, Object>> query = qr.query(sql1, new MapListHandler(),uid);
			List<Friend> friends = new ArrayList<Friend>();
			for(Map<String,Object> map:query){
				String fid = (String) map.get("fid");
				String username = (String) map.get("username");
				List<Message> msgs = findChatLogByUid(fid,uid);
				Friend f = new Friend();
				f.setUid(fid);
				f.setUsername(username);
				f.setMessage(msgs);
				friends.add(f);
			}
			return friends;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	public List<Message> findChatLogByUid(String fid,String uid){
		String sql = "select `from`,`to`,message,currentTime from t_chat_log where `from` = ? and `to` = ?";
		try {
			return qr.query(sql, new BeanListHandler<Message>(Message.class),fid,uid);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void updateState(boolean state ,String uid) {
		String sql = "update t_user set state = ? where uid = ?";
		try {
			qr.update(sql,state,uid);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void saveMessage(String from, String to, long currentTime, String message) {
		String sql = "insert into t_chat_log(`from`,`to`,currentTime,message) values(?,?,?,?)";
		try {
			qr.update(sql,from,to,currentTime,message);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
}
